#include "menuwidget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QDebug>
#include <QPushButton>

#define BACKGROUND_COLOR QColor(74, 75, 76, 220)
#define RADIUS 15
#define SPLIT_LINE_COLOR QColor(30, 30, 30)
#define SPLIT_LINE_HEIGHT 1
#define ITEM_HEIGHT 30
#define BORDER 4
#define WIDTH 120

MenuWidget::MenuWidget(const QList<QString> &item_list, QWidget *parent) : QWidget(parent)
{
    setAttribute(Qt::WA_TranslucentBackground);  // 设置窗口背景透明
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);  // 让窗口无边框

    qDebug() << "MenuWidget创建了";

    int top_y = 0;
    for (const auto & word : item_list)
    {
        if (word == "")  // 添加分割线
        {
            split_line_y.push_back(top_y + 2);
            top_y += SPLIT_LINE_HEIGHT;
        }
        else
        {
            QPushButton *item = new QPushButton(this);
            item->setText(word);
            setStyleSheet("background-color: rgba(0, 0, 0, .0); color: white;");
            item->resize(WIDTH - BORDER * 2, ITEM_HEIGHT);
            item->move(BORDER, top_y + BORDER);
            top_y += BORDER + ITEM_HEIGHT;

            connect(item, &QPushButton::clicked, [=]()
            {
                emit clicked_item(item->text());
            });
        }
    }

    setFixedSize(WIDTH, BORDER + top_y);
}

void MenuWidget::paintEvent(QPaintEvent * ev)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);  // 设置抗锯齿

    QPen pen(BACKGROUND_COLOR);
    pen.setWidth(1);  // 设置边框为 1 像素
    painter.setPen(pen);

    QBrush brush(BACKGROUND_COLOR);
    painter.setBrush(brush);

    QRectF rect(0, 0, this->width(), this->height());  // 画一个和窗口一样大的矩形
    painter.drawRoundedRect(rect, RADIUS, RADIUS);  // 设置矩形的圆角

    // 画分割线
    pen.setColor(SPLIT_LINE_COLOR);
    brush.setColor(SPLIT_LINE_COLOR);
    painter.setPen(pen);
    painter.setBrush(brush);
    for (const auto &split_y : split_line_y)
    {
        painter.drawRect(QRect(BORDER, split_y, WIDTH - BORDER * 2, SPLIT_LINE_HEIGHT));
    }
}

MenuWidget::~MenuWidget()
{
    qDebug() << "MenuWidget 销毁了";
}
